//
//  QRCodeViewController.m
//  Btpin
//
//  Created by Vic on 2019/5/3.
//  Copyright © 2019 Vic. All rights reserved.
//



#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "QRCodeBackgroundView.h"
#import "QRCodeScanView.h"

#define ScanY (181*Scale)           //扫描区域y
#define ScanWidth (186*Scale)       //扫描区域宽度
#define ScanHeight (186*Scale)      //扫描区域高度

@interface QRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    AVCaptureSession *session;
    AVCaptureVideoPreviewLayer *previewLayer;
    
    UIView *signinBgView;
}
@end

@implementation QRCodeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self signinUI];
}
- (void)initUI {
    self.navigationItem.title = @"电脑编辑";
    
    self.view.backgroundColor = COLOR_OF_BLACK;
    UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, 0, WIDTH, 150*Scale) text:@"请在电脑浏览器打开\n\nsao.btpin.com\n\n扫描网页中的二维码登录网页端进行编辑" textColor:COLOR_OF_WHITE font:Font_16];
    topLbl.numberOfLines = 0;
    topLbl.lineBreakMode = NSLineBreakByWordWrapping;
    topLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:topLbl];
    
    NSError *error = nil;
    // 初始化会话
    session = [[AVCaptureSession alloc] init];
    // 设置会话设置输出质量
    session.sessionPreset = AVCaptureSessionPresetMedium;
    
    // 获取需要的设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handling the error appropriately.
        SVPHUDError(@"您的设备暂时不支持该功能");
        return;
    }
    [session addInput:input];
    
    dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
    AVCaptureMetadataOutput *output2 = [[AVCaptureMetadataOutput alloc] init];
    if ([session canAddOutput:output2]) {
        [session addOutput:output2];
        [output2 setMetadataObjectsDelegate:self queue:queue];
        
        // 设置为二维码类型（AVMetadataObjectTypeQRCode），
        // 还有其他类型，可以去接口文件里查看
        [output2 setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
        
        // Start the session running to start the flow of data
        [session startRunning];
    }
    
    UIImageView *imgView = [UIToolsControl initImageViewWithFrame:CGRectMake(70*Scale-5*Scale, EndY(topLbl)+30*Scale-5*Scale, (WIDTH-130*Scale), (WIDTH-130*Scale)) imageName:@"qr_bg_icon"];
    [self.view addSubview:imgView];
    
    //预览层的生成，实时获取摄像头数据
    previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    previewLayer.frame = CGRectMake(70*Scale, EndY(topLbl)+30*Scale, (WIDTH-140*Scale), (WIDTH-140*Scale));
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:previewLayer];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count > 0) {
        [session stopRunning];
        //获得扫描数据，最后一个是最新扫描的数据
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        // 结果  object.stringValue
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", object.stringValue);
            [self qrText:object.stringValue];
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"没有扫描到数据");
            SVPHUDError(@"请对准屏幕的二维码");
            [self->session startRunning];
        });
    }
}
- (void)qrText:(NSString *)text {
    SVPHUDShow;
    NSString *action = @"login";
    switch (self.pushVCType) {
        case VCPushTypeOfHome: {
            action = @"login";
        } break;
        case VCPushTypeOfEditPersonalResume: {
            action = @"edit_resume";
        } break;
        case VCPushTypeOfEditCompanyInfo: {
            action = @"company_info";
        } break;
        case VCPushTypeOfPostJob: {
            action = @"create_jobs";
        } break;
        default:
            break;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:text forKey:@"scan_code"];
    [dic setObject:action forKey:@"action"];
    [BaseNetManager requestWithMethod:POST path:Signin_QR_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            self->signinBgView.hidden = NO;
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
            [self->session startRunning];
        }
    } failurBlock:^(NSError * _Nonnull error) {
        SVPHUDError(NetErrorAlertText);
//        [self->session startRunning];
    }];
}
- (void)signinBtnTap {
    self.edit(YES);
    
    signinBgView.hidden = YES;
    [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
}
- (void)delayClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)signinUI {
    signinBgView = [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) backgroundColor:COLOR_OF_WHITE];
    [[UIApplication sharedApplication].keyWindow addSubview:signinBgView];
    signinBgView.hidden = YES;
    
    UIImage *img = [UIImage imageNamed:@"qr_signin_icon"];
    UIImageView *signinImgView = [UIToolsControl initImageViewWithFrame:CGRectMake((WIDTH-img.size.width)*0.5, 130*Scale, img.size.width, img.size.height) imageName:@"qr_signin_icon"];
    [signinBgView addSubview:signinImgView];
    
    UILabel *signinTopLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, EndY(signinImgView)+50*Scale, WIDTH, 45*Scale) text:@"已登录电脑端比特聘" textColor:THEMECOLOR_OF_ORANGE font:Font_15];
    signinTopLbl.textAlignment = NSTextAlignmentCenter;
    [signinBgView addSubview:signinTopLbl];
    
    UILabel *signinBottomLbl = [UIToolsControl initLabelWithFrame:CGRectMake(0, EndY(signinTopLbl), WIDTH, 45*Scale) text:@"请在网页端进行编辑，内容会同步到手机端" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_15];
    signinBottomLbl.textAlignment = NSTextAlignmentCenter;
    [signinBgView addSubview:signinBottomLbl];
    
    UIButton *signinBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, HEIGHT-150*Scale, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(signinBtnTap) title:@"完成" titleColor:COLOR_OF_WHITE];
    signinBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    signinBtn.layer.cornerRadius = 23*Scale;
    signinBtn.layer.masksToBounds = YES;
    signinBtn.titleLabel.font = Font(Font_18);
    [signinBgView addSubview:signinBtn];
}

@end
